package com.jinyijia.admin.interfaces.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;

import java.nio.charset.Charset;

public class HttpHeadUtil {
  public static HttpEntity<String> addHeader () {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "text/html");
    headers.add(
        "Accept",
        "text/html,application/xhtml+xml,application/xml,application/json;q=0.9,image/webp,*/*;q=0.8");
    headers.add("Accept-Encoding", "gzip, deflate, sdch");
    headers.add("Cache-Control", "max-age=0");
    headers.add("Connection", "keep-alive");
    HttpEntity<String> requestEntity = new HttpEntity<>(headers);
    return requestEntity;
  }

  public static HttpEntity<String> addBody(Object body) {
    HttpHeaders headers = new HttpHeaders();
    MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
    MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
    // 请求体
    headers.setContentType(mediaType);
    //提供json转化功能
    ObjectMapper mapper = new ObjectMapper();
    String str = null;
    try {
      if (body!=null) {
        str = mapper.writeValueAsString(body);
      }
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
    // 发送请求
    return new HttpEntity<>(str, headers);
  }
}
